library(tidyverse) # for graphing and data cleaning
library(gardenR) # for Lisa's garden data
library(lubridate) # for date manipulation
library(ggthemes) # for even more plotting themes
library(geofacet) # for special faceting with US map layout
theme_set(theme_minimal()) # My favorite ggplot() theme :)
# Lisa's garden data
data("garden_harvest")
# Seeds/plants (and other garden supply) costs
data("garden_spending")
# Planting dates and locations
data("garden_planting")
# Tidy Tuesday data
kids <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-09-15/kids.csv')
Before starting your assignment, you need to get yourself set up on GitHub and make sure GitHub is connected to R Studio. To do that, you should read the instruction (through the “Cloning a repo” section) and watch the video here. Then, do the following (if you get stuck on a step, don’t worry, I will help! You can always get started on the homework and we can figure out the GitHub piece later):
keep_md: TRUE in the YAML heading. The .md file is a markdown (NOT R Markdown) file that is an interim step to creating the html file. They are displayed fairly nicely in GitHub, so we want to keep it and look at it there. Click the boxes next to these two files, commit changes (remember to include a commit message), and push them (green up arrow).Put your name at the top of the document.
For ALL graphs, you should include appropriate labels.
Feel free to change the default theme, which I currently have set to theme_minimal().
Use good coding practice. Read the short sections on good code with pipes and ggplot2. This is part of your grade!
When you are finished with ALL the exercises, uncomment the options at the top so your document looks nicer. Don’t do it before then, or else you might miss some important warnings and messages.
These exercises will reiterate what you learned in the “Expanding the data wrangling toolkit” tutorial. If you haven’t gone through the tutorial yet, you should do that first.
garden_harvest data to find the total harvest weight in pounds for each vegetable and day of week (HINT: use the wday() function from lubridate). Display the results so that the vegetables are rows but the days of the week are columns.garden_harvest %>%
mutate(day = wday(date, label = T)) %>%
group_by(vegetable, day) %>%
summarize(total_wt_lbs = round((sum(weight) * 0.00220462), 2)) %>%
arrange(day) %>%
pivot_wider(id_cols = vegetable,
names_from = day,
values_from = total_wt_lbs)
garden_harvest data to find the total harvest in pound for each vegetable variety and then try adding the plot from the garden_planting table. This will not turn out perfectly. What is the problem? How might you fix it?garden_harvest %>%
group_by(vegetable, variety) %>%
summarize(total_wt_lbs = round((sum(weight) * 0.00220462), 2)) %>%
left_join(garden_planting,
by = c("vegetable", "variety")) %>%
select(vegetable:plot)
There are a few problems. Some of the vegetable varieties have been plotted in multiple plots, creating duplicate rows of information to include both plot locations. Also, there are some varieties with missing plots which is something we must be considerate of moving forward (these are most likely perennials or reseed). You could try only selecting the first plot location which would reduce some of the unwanted duplicate entries.
garden_harvest and garden_spending datasets, along with data from somewhere like this to answer this question. You can answer this in words, referencing various join functions. You don’t need R code but could provide some if it’s helpful.You could group by vegetable and find the total amount you spent on seeds in the garden_spending table, and also group by vegetable in the garden_harvest table and find the total amount you harvested for each by weight. Then you could join these tables by vegetable so you have the total weight and total amount spent. Using data from a store, you could also join the prices to the table by vegetable, multiply the store price by your weight, and then find the difference between how much you paid for the seeds and how much it would have cost.
garden_harvest %>%
filter(vegetable == "tomatoes") %>%
group_by(variety) %>%
mutate(first_harvest = min(date)) %>%
mutate(tot_wt = sum(weight) * 0.00220462) %>%
ggplot() +
geom_col(aes(x = tot_wt, y = fct_reorder(variety, first_harvest))) +
labs(x = "", y = "", title = "Total harvest weight in lbs by tomato variety")
garden_harvest data, create two new variables: one that makes the varieties lowercase and another that finds the length of the variety name. Arrange the data by vegetable and length of variety name (smallest to largest), with one row for each vegetable variety. HINT: use str_to_lower(), str_length(), and distinct().garden_harvest %>%
mutate(lwr_case = str_to_lower(variety),
len_of_var = str_length(variety)) %>%
distinct(variety, .keep_all = T) %>%
arrange(vegetable, len_of_var) %>%
select(vegetable, variety, lwr_case, len_of_var)
garden_harvest data, find all distinct vegetable varieties that have “er” or “ar” in their name. HINT: str_detect() with an “or” statement (use the | for “or”) and distinct().garden_harvest %>%
mutate(lwr_case = str_to_lower(variety)) %>%
mutate(has_ar_er = str_detect(lwr_case, "ar|er")) %>%
distinct(variety, .keep_all = T) %>%
filter(has_ar_er == TRUE) %>%
arrange(vegetable)
In this activity, you’ll examine some factors that may influence the use of bicycles in a bike-renting program. The data come from Washington, DC and cover the last quarter of 2014.
{300px}
{300px}
Two data tables are available:
Trips contains records of individual rentalsStations gives the locations of the bike rental stationsHere is the code to read in the data. We do this a little differently than usualy, which is why it is included here rather than at the top of this file. To avoid repeatedly re-reading the files, start the data import chunk with {r cache = TRUE} rather than the usual {r}.
data_site <-
"https://www.macalester.edu/~dshuman1/data/112/2014-Q4-Trips-History-Data.rds"
Trips <- readRDS(gzcon(url(data_site)))
Stations<-read_csv("http://www.macalester.edu/~dshuman1/data/112/DC-Stations.csv")
NOTE: The Trips data table is a random subset of 10,000 trips from the full quarterly data. Start with this small data table to develop your analysis commands. When you have this working well, you should access the full data set of more than 600,000 events by removing -Small from the name of the data_site.
It’s natural to expect that bikes are rented more at some times of day, some days of the week, some months of the year than others. The variable sdate gives the time (including the date) that the rental started. Make the following plots and interpret them:
sdate. Use geom_density().Trips %>%
ggplot() +
geom_density(aes(x = sdate)) +
labs(x = "", y = "", title = "Density of bike rental events by day")
mutate() with lubridate’s hour() and minute() functions to extract the hour of the day and minute within the hour from sdate. Hint: A minute is 1/60 of an hour, so create a variable where 3:30 is 3.5 and 3:45 is 3.75.Trips %>%
mutate(time_of_day = hour(sdate) + (minute(sdate) * (1/60))) %>%
ggplot() +
geom_density(aes(x = time_of_day)) +
labs(x = "", y = "", title = "Density of bike rental events by time of day in hours")
Trips %>%
mutate(day_of_week = wday(sdate, label = T)) %>%
ggplot() +
geom_bar(aes(y = fct_rev(day_of_week))) +
labs(x = "", y = "", title = "Number of bike rentals by day of the week")
Trips %>%
mutate(time_of_day = hour(sdate) + (minute(sdate) * (1/60)),
day_of_week = wday(sdate, label = T)) %>%
ggplot() +
geom_density(aes(x = time_of_day)) +
facet_wrap(~ day_of_week) +
labs(x = "", y = "", title = "Density of bike rental events by time of day in hours and day of the week")
There are some clear patterns shown in this plot. On weekdays, there are large peaks at around 8 am and 6 pm, coinciding with typical working hours. On the weekends, it is more of a standard bell curve distribution with the peak of rentals being around early afternoon.
The variable client describes whether the renter is a regular user (level Registered) or has not joined the bike-rental organization (Causal). The next set of exercises investigate whether these two different categories of users show different rental behavior and how client interacts with the patterns you found in the previous exercises.
fill aesthetic for geom_density() to the client variable. You should also set alpha = .5 for transparency and color=NA to suppress the outline of the density function.Trips %>%
mutate(time_of_day = hour(sdate) + (minute(sdate) * (1/60)),
day_of_week = wday(sdate, label = T)) %>%
ggplot() +
geom_density(aes(x = time_of_day, fill = client), alpha = 0.5, color = NA) +
facet_wrap(~ day_of_week) +
labs(x = "", y = "", title = "Density of bike rental events by time of day in hours and client status", fill = "Client")
position = position_stack() to geom_density(). In your opinion, is this better or worse in terms of telling a story? What are the advantages/disadvantages of each?Trips %>%
mutate(time_of_day = hour(sdate) + (minute(sdate) * (1/60)),
day_of_week = wday(sdate, label = T)) %>%
ggplot() +
geom_density(aes(x = time_of_day, fill = client),
alpha = 0.5,
color = NA,
position = position_stack()) +
facet_wrap(~ day_of_week) +
labs(x = "", y = "", title = "Density of bike rental events by time of day in hours and client status", fill = "Client")
In my opinion, I think the first graph (#11) does a better job at telling the story because you can more easily distinguish the patterns between the types of clients. The second graph makes it appear more like both types peak around 8 am and 6 pm, however we know that’s not the case from the first graph. The second graph is nicer to see the combined trends, but if you want to break it down by client the first graph is better.
position = position_stack()). Add a new variable to the dataset called weekend which will be “weekend” if the day is Saturday or Sunday and “weekday” otherwise (HINT: use the ifelse() function and the wday() function from lubridate). Then, update the graph from the previous problem by faceting on the new weekend variable.Trips %>%
mutate(time_of_day = hour(sdate) + (minute(sdate) * (1/60)),
day_of_week = wday(sdate, label = T),
weekend = ifelse(day_of_week %in% c("Sat", "Sun"), "Weekend", "Weekday")) %>%
ggplot() +
geom_density(aes(x = time_of_day, fill = client), alpha = 0.5, color = NA) +
facet_wrap(~ weekend) +
labs(x = "", y = "", title = "Density of bike rental events by time of day in hours and day type", fill = "Client")
client and fill with weekday. What information does this graph tell you that the previous didn’t? Is one graph better than the other?Trips %>%
mutate(time_of_day = hour(sdate) + (minute(sdate) * (1/60)),
day_of_week = wday(sdate, label = T),
weekend = ifelse(day_of_week %in% c("Sat", "Sun"), "Weekend", "Weekday")) %>%
ggplot() +
geom_density(aes(x = time_of_day, fill = weekend), alpha = 0.5, color = NA) +
facet_wrap(~ client) +
labs(x = "", y = "", title = "Density of bike rental events by time of day in hours and client status", fill = "Day")
The two graphs show the same information just with a different ordering/stacking. The second one makes it easier to see differences within the clients based on the day, while the first makes it easier to see differences within the type of day based on clients. Both are acceptable graphs, but if I had to pick one I would use the second one.
Stations to make a visualization of the total number of departures from each station in the Trips data. Use either color or size to show the variation in number of departures. We will improve this plot next week when we learn about maps!Trips %>%
group_by(sstation) %>%
summarize(n = n()) %>%
left_join(Stations,
by = c("sstation" = "name")) %>%
ggplot() +
geom_point(aes(x = long, y = lat, color = n)) +
labs(x = "Longitude", y = "Latitude", title = "Total number of departures by station", color = "")
Trips %>%
group_by(sstation) %>%
summarize(total = n(),
prop_cas = sum(client == "Casual") / total) %>%
left_join(Stations,
by = c("sstation" = "name")) %>%
ggplot() +
geom_point(aes(x = long, y = lat, color = prop_cas)) +
labs(x = "Longitude", y = "Latitude", title = "Proportion of casual rider departures by station", color = "")
as_date(sdate) converts sdate from date-time format to date format.top_ten_by_date <- Trips %>%
mutate(date = as_date(sdate)) %>%
group_by(sstation, date) %>%
summarize(n = n()) %>%
arrange(desc(n)) %>%
ungroup() %>%
slice_max(n, n = 10, with_ties = F)
top_ten_by_date
Trips %>%
mutate(date = as_date(sdate)) %>%
inner_join(top_ten_by_date,
by = c("sstation" = "sstation", "date" = "date")) %>%
select(-c("n"))
Trips %>%
mutate(date = as_date(sdate)) %>%
inner_join(top_ten_by_date,
by = c("sstation" = "sstation", "date" = "date")) %>%
select(-c("n")) %>%
mutate(day_of_week = wday(sdate, label = T)) %>%
count(client, day_of_week) %>%
group_by(client) %>%
mutate(prop = n/sum(n)) %>%
select(-c("n")) %>%
pivot_wider(names_from = client,
values_from = prop) %>%
arrange(day_of_week)
This table indicates that registered users are more active during the week, while casual users are more active on the weekends. This coincides with previous results that indicated influxes of registered users around the start and end of regular business hours. Many registered users probably use these to commute to work on a regular basis, while casual riders may tend to use the bikes more for leisure activities on the weekends.
DID YOU REMEMBER TO GO BACK AND CHANGE THIS SET OF EXERCISES TO THE LARGER DATASET? IF NOT, DO THAT NOW.
This problem uses the data from the Tidy Tuesday competition this week, kids. If you need to refresh your memory on the data, read about it here.
facet_geo(). The graphic won’t load below since it came from a location on my computer. So, you’ll have to reference the original html on the moodle page to see it.kids <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-09-15/kids.csv')
kids %>%
filter(variable == "lib", year == "1997"|year == "2016") %>%
select(state, year, inf_adj_perchild) %>%
arrange(state) %>%
ggplot(aes(x = year, y = inf_adj_perchild)) +
geom_line() +
facet_geo(vars(state)) +
labs(x = "", y = "", title = "Change in public spending on libraries from 1996 to 2016", subtitle = "Thousands of dollars spent per child, adjusted for inflation") +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank(),
axis.title.y=element_blank(),
axis.text.y=element_blank(),
axis.ticks.y=element_blank(),
plot.title = element_text(face = "bold", hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5),
plot.background = element_rect(fill = "slategrey"))
DID YOU REMEMBER TO UNCOMMENT THE OPTIONS AT THE TOP?